package thread;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Miyako
 * @Date: 2024-07-22-19:59
 * @Description:
 */
public class MChartServer {
    private Socket socket;
    private ServerSocket serverSocket;
    private Map<String, PrintWriter> map = new HashMap<>();
    private static final int port;

    static {
        port = 8888;
    }

    MChartServer() {
        try {
            System.out.println("服务器启动中...");
            serverSocket = new ServerSocket(port);
            System.out.println("服务器启动成功");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务器启动失败");
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                socket = serverSocket.accept();//阻塞,直到有客户端连接
                System.out.println("一个客户端连接了");
                new Thread(new ClientHander()).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务器异常");
        }
    }

    class ClientHander implements Runnable {
        private String nickName;

        @Override
        public void run() {
            String data;
            BufferedReader br = null;
            PrintWriter pw = null;
            try {
                br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()));
                pw = new PrintWriter(
                        new OutputStreamWriter(
                                socket.getOutputStream()), true);
                nickName = br.readLine();//接收昵称
                synchronized (MChartServer.this) {
                    map.put(nickName, pw);
                }
                sendMessageTOAllClient(nickName+"上线啦");
                while ((data = br.readLine()) != null) {
                    System.out.println(data);
                    if (data.startsWith("@")) {
                        sendMessageToAClient(data);
                    } else {
                        sendMessageTOAllClient(data);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    map.remove(nickName);
                    if (br == null) br.close();
                    if (pw == null) pw.close();
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }


        }

        private void sendMessageToAClient(String data) {
            data = data.substring(1);
            String[] S = data.split(":", 2);
            map.get(S[0]).println(nickName + ":" + S[1]);
        }

        private void sendMessageTOAllClient(String data) {//广播
            map.forEach((k, v) -> {
                if (k != nickName) map.get(k).println(nickName + ":" + data);
            });
        }
    }

    public static void main(String[] args) {
        new MChartServer().start();
    }
}
